<template>
  <div class="content_bg">
    <el-card class="box-card">
      <h3 class="page_title">车辆管理</h3>
      <el-card class="box-card asset_form">
        <el-form :model="createForm" :rules="rules" ref="createForm" label-width="100px" class="demo-ruleForm" size="small">
          <el-row>
            <el-col :span="10">
              <el-form-item label="车辆名称" prop="name">
                <el-input v-model="createForm.name" size="small"></el-input>
              </el-form-item>
              <el-form-item label="车牌号码" prop="carNum">
                <el-input v-model="createForm.carNum" size="small"></el-input>
              </el-form-item>
               <el-form-item label="项目" prop="project" style="width: 100%">
                  <el-select v-model="createForm.project" placeholder="请选择" style="width:100%">
                    <el-option
                      v-for="item in projectArr"
                      :key="item.projectId"
                      :label="item.name"
                      :value="item.projectId">
                    </el-option>
                  </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="绑定设备" prop="bind" style="width: 100%">
                  <el-select v-model="createForm.bind" clearable placeholder="请选择" style="width:100%">
                    <el-option
                      v-for="item in deviceArr"
                      :key="item.deviceId"
                      :label="item.deviceName"
                      :value="item.deviceId">
                    </el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="设备描述" prop="desc">
                <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 4}" v-model="createForm.desc"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="operate_submit">
              <el-button type="warning" size="small" v-if="roleIdList.includes(22)" class="operate_create" @click="createNew('add')"><i class="fa fa-plus"></i> 创建</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <h3 class="page_title">车辆列表</h3>
      <el-table ref="table" class="fix_top" :data="tableData" style="width: 100%" :max-height="client.height-102-40-380" highlight-current-row
        @cell-mouse-enter="handleCurrentChange" @cell-mouse-leave="removeCurrentChange">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form :model="updateForm" :rules="rules" ref="updateForm" label-width="100px" label-position="left" size="small" inline
              class="demo-table-expand">
              <el-row>
                <el-col :span="10">
                  <el-form-item label="车辆名称" prop="name" style="width: 100%">
                    <el-input v-model="updateForm.name" size="small" style="width: 100%"></el-input>
                  </el-form-item>
                  <el-form-item label="车牌号码" prop="carNum" style="width: 100%">
                    <el-input v-model="updateForm.carNum" size="small" style="width: 100%"></el-input>
                  </el-form-item>
                  <el-form-item label="项目" prop="project" style="width: 100%">
                    <el-select v-model="updateForm.project" placeholder="请选择" style="width:100%">
                      <el-option
                        v-for="item in projectArr"
                        :key="item.projectId"
                        :label="item.name"
                        :value="item.projectId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="绑定设备" prop="bind" style="width: 100%">
                    <el-select v-model="updateForm.bind" clearable placeholder="请选择" style="width:100%">
                      <el-option
                        v-for="item in deviceArr"
                        :key="item.deviceId"
                        :label="item.deviceName"
                        :value="item.deviceId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="设备描述" prop="desc" style="width: 100%">
                    <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 4}" v-model="updateForm.desc" style="width: 100%"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4" class="operate_submit">
                  <div>
                    <el-button type="info" size="small" class="table_ok" @click="createNew('update')">确定</el-button>
                  </div>
                  <div>
                    <el-button type="info" size="small" class="table_cancel" @click="recover(props.row)">取消</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="序号" prop="fNum" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="车辆名称" prop="vehicleName" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="车牌号" prop="plateNumber" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="项目" prop="project" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="绑定设备" prop="bindDeviceName" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="设备描述" prop="vehicleDesc" show-overflow-tooltip>
        </el-table-column>
        <el-table-column min-width="160">
          <template slot-scope="scope">
            <div class="table_operate" v-if="currentRow === scope.row.vehicleId">
              <el-button-group>
                <el-button v-if="roleIdList.includes(23)" class="table_operate_btn table_show" @click.native.prevent="rowExpansion(scope.row)"
                  type="text" size="small">
                <i class="fa fa-edit"></i>  修改
                </el-button>
                <el-button v-if="roleIdList.includes(24)" class="table_operate_btn table_delete" @click.native.prevent="del(scope.$index, scope.row.vehicleId, scope.row)"
                  type="text" size="small">
                <i class="fa fa-trash-o"></i>  移除
                </el-button>
              </el-button-group>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block page_detail">
        <el-pagination @current-change="handlePageCurrentChange" :current-page.sync="pageCurrent" :page-size="pageSize" layout="prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
  import {
    mapState
  } from 'vuex';
  import {
    vehicleManagement,
    deviceManagement,
    projectManagement
  } from '../../../service/service_zbw';
  import {
    dataSort,
    formCheck,
    trim
  } from '../../../lib/utils';

  export default {

    computed: {
      ...mapState({
        client: state => state.client,
        userRealDept: state => state.userRealDept,
        roleIdList: state => state.roleIdList,
      }),
    },
    data() {
      //车辆名称校验
      const checkName = (rule, value, callback) => {
        let str = trim(value);
        if (!str) {
          return callback(new Error('车辆名称不能为空'));
        } else {
          callback();
        }
      };
      //车牌号校验
      const checkCarNum = (rule, value, callback) => {
        let reg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
        let str = trim(value);
        if (!str) {
          return callback(new Error('车牌号不能为空'));
        } else {
          if (!reg.test(str)) {
            return callback(new Error('车牌号格式不正确'));
          }
          callback();
        }
      };
      //项目校验
      const checkProject = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('项目不能为空'));
        } else {
          if (value.length <= 0) {
            return callback(new Error('项目不能为空'));
          }
          callback();
        }
      };
      return {
        createForm: {
          name: '',
          project: '',
          carNum: '',
          desc: '',
          bind:''
        },
        updateForm: {
          vehicleId: '',
          name: '',
          project: '',
          carNum: '',
          desc: '',
          bind: ''
        },
        rules: {
          name: [{
            required: true,
            validator: checkName,
            trigger: 'blur'
          },
            {
              min: 1,
              max: 50,
              message: '长度在 1 到 50 个字符',
              trigger: 'blur'
            }],
          carNum: [{
            required: true,
            validator: checkCarNum,
            trigger: 'blur'
          }],
          project: [{
            required: true,
            validator: checkProject,
            trigger: 'change'
          }],
          desc: [{
              message: '请输入车辆名称',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 50,
              message: '长度在 1 到 50 个字符',
              trigger: 'blur'
            }
          ]
        },
        optionProps: {
          value: 'deptId',
          label: 'deptName'
        },
        tableData: [],
        currentRow: '',
        currentPage: 5,
        total: 0,
        currentRow: '',
        pageCurrent: 1,
        pageSize: 50,
        lastSelectRow: null,
        copyUpdateForm: null,
        deviceArr: [],
        projectArr: [],
      }
    },
    methods: {
      init() {
        this.getConditions();
        this.getBindDevice();
        this.getProject();
      },
      /**
       * 整理查询条件
       */
      getConditions() {
        let param = {
          pageCurrent: this.pageCurrent,
          pageSize: this.pageSize,
        };
        this.getTableData(param)
      },
      /**
       * 获取表格数据
       */
      async getTableData(param) {
        let res = await vehicleManagement.getTableData(param);
        if (res.success) {
          this.total = res.obj.itemTotal;
          this.tableData = dataSort(res.obj.items, this.pageCurrent);
          //   for (let i of this.tableData) {
          //     i.resDeptId = this.format(i.resDeptId);
          //   }
        } else {
          this.total = 0;
          this.tableData = [];
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      },
      /**
       *获取可绑定设备
       */
      async getBindDevice(param){
        let res = await vehicleManagement.bindDevices(param);
        if (res.result) {
          this.deviceArr = res.obj;
        }else{
          this.deviceArr = []
        }
      },
       /**
       *获取可选择项目
       */
      async getProject(param){
        let res = await projectManagement.getProList(param);
        if (res.success) {
          this.projectArr = res.obj;
        }else{
          this.projectArr = []
        }
      },
      format(val) {
        try {
          let arr = val.split(',');
          for (let i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * 1;
          }
          return arr;
        } catch (error) {
          console.log(error)
        }
      },
      /**
       * 新增/修改
       */
      async createNew(status) {
        let param = {};
        let flag = false;
        let res = null;
        if (status === 'add') {
          flag = formCheck(this, 'createForm');
          if (flag) {
            param = {
              vehicleId: '',
              vehicleName: this.createForm.name,
              plateNumber: this.createForm.carNum,
              projectId: this.createForm.project,
              bindDevice: this.createForm.bind,
              vehicleDesc: this.createForm.desc,
            };
            res = await vehicleManagement.addTableData(param);
          }
        } else {
          flag = formCheck(this, 'updateForm');
          if (flag) {
            param = {
              vehicleId: this.updateForm.vehicleId,
              vehicleName: this.updateForm.name,
              plateNumber: this.updateForm.carNum,
              projectId: this.updateForm.project,
              bindDevice: this.updateForm.bind,
              vehicleDesc: this.updateForm.desc,
              status: this.updateForm.status
            };
            res = await vehicleManagement.updateTableData(param);
          }
        }
        if (res) {
          if (res.success) {
            if (status === 'add') {
              this.resetForm('createForm');
            } else {
              this.resetForm('updateForm');
            }
            this.getConditions();
            this.$message({
              message: res.msg,
              type: 'success'
            });
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            });
          }
        }
      },
      /**
       * hover表格某一行获取id
       */
      handleCurrentChange(val) {
        //当删除当前行时,val值不存在
        try {
          this.currentRow = val.vehicleId;
        } catch (error) {
          this.currentRow = '';
        }
      },
      removeCurrentChange() {
        this.currentRow = '';
      },
      /**
       * 通过详情按钮控制表格展开或闭合
       */
      rowExpansion(row) {
        this.lastSelectRow = row;
        this.$refs.table.toggleRowExpansion(row, true);
        this.updateForm = {
          vehicleId: row.vehicleId,
          name: row.vehicleName,
          carNum: row.plateNumber,
          project: row.projectId,
          bind: row.bindDevice || '',
          desc: row.vehicleDesc,
          status: row.status
        };
      },
      recover(val) {
        this.$refs.table.toggleRowExpansion(val, false);
      },
      del(index, id, row) {
        this.$confirm('您确定要删除车辆“' + row.vehicleName + '”吗？', '询问', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.deleteRow(index, id);
        }).catch(() => {
          //TODO
        });
      },
      /**
       * 删除
       */
      async deleteRow(index, id) {
        let param = id;
        let res = await vehicleManagement.delTableData(param);
        if (res.success) {
          this.tableData.splice(index, 1);
          this.$message({
            message: res.msg,
            type: 'success'
          });
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      },
      /**
       * 分页改变
       */
      handlePageCurrentChange(val) {
        this.pageCurrent = val;
        this.getConditions();
      },
      /**
       *
       */
      handleChange(value) {
        console.log(value);
      },
      /**
       * 表单清空
       */
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    },
    watch: {
      lastSelectRow(newval, oldval) {
        this.$refs.table.toggleRowExpansion(oldval, false);
      }
    },
    mounted() {
      this.init();
    }
  }

</script>

<style scoped>
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  .box-card {
    width: calc(100% - 32px);
    height: inherit;
  }

  .table_show,
  .table_show:link,
  .table_show:visited,
  .table_show:hover,
  .table_show:active {
    background: #535953;
    color: #fff;
  }

  .table_delete,
  .table_delete:link,
  .table_delete:visited,
  .table_delete:hover,
  .table_delete:active {
    background: #d9524e;
    color: #fff;
  }

  .table_ok {
    width: 80px;
    background: #409eff;
    color: #fff;
    border-color: #409eff;
  }

  .table_cancel {
    width: 80px;
    background: #d8d8d8;
    color: #666;
    border: 1px solid #999;
  }

  .page_title {
    padding: 20px 0 15px 30px;
    font-size: 16px;
    font-weight: bold;
    color: #666;
  }

  .el-table td,
  .el-table th.is-leaf {
    border-bottom: 1px solid #e6ebf5;
  }

</style>

